/**
 * 
 */
package com.haisen.lee.thread;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.cyberneko.html.parsers.DOMParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.haisen.lee.domain.FormDictionary;
import com.haisen.lee.service.IDomParser;
import com.haisen.lee.service.IDomParserThread;
import com.haisen.lee.util.DOMParserType;

/**
 * @author Haisen Lee
 * 
 */
public class HtmlDomParserThreadImpl implements IDomParserThread {

	private static final DOMParserType selfDOMParserType = DOMParserType.HTML;
	private URL url = null;
	@Autowired
	private IDomParser htmlDomParserImpl;

	/**
	 * 
	 */
	public HtmlDomParserThreadImpl() {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
		DOMParser parser = new DOMParser();
		URLConnection urlCon;
		try {
			urlCon = url.openConnection();

			InputStream is = urlCon.getInputStream();

			parser.parse(new InputSource(is));

			Document doc = parser.getDocument();
			NodeList htmlNodeList = doc.getElementsByTagName(selfDOMParserType
					.getName());
			for (int i = 0; i < htmlNodeList.getLength(); i++) {
				Node htmlNode = htmlNodeList.item(i);
				htmlDomParserImpl.contentExtractor(htmlNode);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void setHtmlDomParserImpl(IDomParser htmlDomParserImpl) {
		this.htmlDomParserImpl = htmlDomParserImpl;
	}

	public URL getUrl() {
		return url;
	}

	public void setUrl(URL url) {
		this.url = url;
	}

	@Override
	public void setParserNode(Node root) {

	}

	@Override
	public void setFormDictionary(FormDictionary formDictionary) {
		// TODO Auto-generated method stub
		
	}

}
